package com.store.app.activity;


import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.store.app.BaseActivity;
import com.store.app.R;
import com.store.app.utils.Utils;
import com.store.app.widget.ProgressWebView;

/**
 * 专门用于显示广告的页面，会传递一个url过来
 */
public class WebViewAdActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, OnClickListener{


    private ImageView public_ll_return;
    private TextView tvTitle;
    private SwipeRefreshLayout sw;
    private String urls;                            //要打开的页面
    private ProgressWebView webView;
    private ProgressBar progressbar;
    private TextView tv_right;
    private RelativeLayout loadfail;
    private LinearLayout lin_loadNull;//加载为空
    private LinearLayout lin_loadfail;  //无网络页面
    private TextView tvReload;
    private boolean needX = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview_more);
        urls = getIntent().getStringExtra("url");
        needX = getIntent().getBooleanExtra("needX",true);
        Log.v("zyl", "url:" + urls);
        initView();
        setWebView();
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.public_ll_return:
                if (webView.canGoBack() && !"about:blank".equals(webView.getUrl())) {
                    webView.goBack();// 返回前一个页面
                } else {
                    finish();
                }
                break;
        }
    }

    public void showLoadResult(int state) {
        //无网络情况
        if (state == 1) {
            loadfail.setVisibility(View.VISIBLE);
            lin_loadfail.setVisibility(View.VISIBLE);
            lin_loadNull.setVisibility(View.GONE);
        }//无数据情况
        else if (state == 2) {
            Log.v("zyl", "无数据");
            loadfail.setVisibility(View.VISIBLE);
            lin_loadfail.setVisibility(View.GONE);
            lin_loadNull.setVisibility(View.VISIBLE);
        }//都不显示
        else {
            loadfail.setVisibility(View.GONE);
        }
    }
    private void initView() {
        public_ll_return = (ImageView) findViewById(R.id.public_ll_return);
        public_ll_return.setOnClickListener(this);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        sw = (SwipeRefreshLayout) findViewById(R.id.sw);
        sw.setOnRefreshListener(this);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        progressbar.setOnClickListener(this);
        webView = (ProgressWebView) findViewById(R.id.onlcon_web);
        webView.setOnClickListener(this);

        tv_right = (TextView) findViewById(R.id.public_tv_right);
        tv_right.setBackgroundResource(R.drawable.pic_icon_close_x);
        tv_right.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        if(needX){
            tv_right.setVisibility(View.VISIBLE);
        }else{
            tv_right.setVisibility(View.GONE);
        }
        loadfail = (RelativeLayout) findViewById(R.id.loadfail);

        lin_loadfail = (LinearLayout) findViewById(R.id.ll_load_fail);//无网络
        lin_loadNull = (LinearLayout) findViewById(R.id.ll_load_null);//无数据
        tvReload = (TextView) findViewById(R.id.tv_reload);
        tvReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                showLoadResult(3);
                webView.clearCache(true);
                webView.clearHistory();
                webView.clearFormData();
                webView.loadUrl(urls);
            }
        });
    }

    private void setWebView() {
        webView.clearCache(true);
        Log.v("zyl", "setWebView urls:" + urls);
        webView.loadUrl(urls);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDefaultTextEncodingName("utf-8");
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);//设置不使用缓存
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {                 // Handle the error
                Log.v("zyl", "onReceivedError网络加载不出来");
                //停止webView的所有操作
                webView.onPause();
                webView.pauseTimers();
                showLoadResult(1);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.v("zyl", "获取到变化的url：" + url);
                String newLayer = getValueByName(url, "newLayer");
                if (!TextUtils.isEmpty(newLayer)) {
                    if (newLayer.equals("true")) {
                        Intent intent = new Intent(WebViewAdActivity.this, WebViewAdActivity.class);
                        intent.putExtra("url", url);
                        startActivity(intent);
                        return true;
                    } else {

                    }
                }
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    return false;
                }
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {

                }
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (url.startsWith("http")) {
                    urls = url;
                }
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                Log.v("zyl", "加载进度：" + newProgress);
                if (newProgress == 100) {
                    progressbar.setVisibility(View.GONE);
                } else {
                    if (progressbar.getVisibility() == View.GONE)
                        progressbar.setVisibility(View.VISIBLE);
                    progressbar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                tvTitle.setText(title);
            }
        });
        webView.addJavascriptInterface(new JSInterface(), "jsObj");
    }


    final class JSInterface {
        private Handler handler = new Handler();

        //上传图片
        @JavascriptInterface
        public void uploadImg(final String s) {
            handler.post(new Runnable() {
                @Override
                public void run() {

                }
            });
        }
    }


    public void onPause() {//继承自Activity
        super.onPause();
        webView.onPause();
        webView.pauseTimers();
        if (isFinishing()) {
            webView.loadUrl("about:blank");
            setContentView(new FrameLayout(this));
        }
    }

    public void onResume() {//继承自Activity
        super.onResume();
        webView.onResume();
        webView.resumeTimers();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack() && !"about:blank".equals(webView.getUrl())) {
            webView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onRefresh() {
        Log.v("zyl", "下拉刷新了");
//        setWebView();
        webView.loadUrl(urls);
        sw.setRefreshing(false);
    }


    public static String getValueByName(String url, String name) {
        String result = "";
        int index = url.indexOf("?");
        String temp = url.substring(index + 1);
        String[] keyValue = temp.split("&");
        for (String str : keyValue) {
            if (str.contains(name)) {
                result = str.replace(name + "=", "");
                break;
            }
        }
        return result;
    }
}
